/**
 * 
 */
package com.imonsoft.common.util;

/**
 * 
 * @author LiQianHui
 * @date 2013-04-17
 * @version 2013
 */
public abstract class IdCardUtil {

	/**
	 * 
	 * @param idCard
	 * @return
	 */
	public static String idCard15To18(String idCard) {
		if (idCard == null || idCard.length() != 15) {
			return idCard;
		}
		int iS = 0;
		// 新身份证号
		String idCardNew = idCard.substring(0, 6);
		// 填在第6位及第7位上填上‘1’，‘9’两个数字
		idCardNew += "19";
		idCardNew += idCard.substring(6);
		// 进行加权求和
		for (int i = 0; i < 17; i++) {
			iS += Integer.valueOf(idCardNew.substring(i, i + 1)).intValue() * iW[i];
		}
		// 取模运算，得到模值
		int iY = iS % 11;
		// 从lastCode中取得以模为索引号的值，加到身份证的最后一位，即为新身份证号。
		idCardNew += szVerCode[iY];

		return idCardNew;
	}

	public static String idCard18To15(String idCard) {
		if (idCard == null || idCard.length() != 18) {
			return idCard;
		}
		// 新身份证号
		String idCardNew = idCard.substring(0, 6) + idCard.substring(8, 17);
		return idCardNew;
	}

	public static String swap15or18(String idCard) {
		if (idCard == null) {
			return null;
		}
		if (idCard.length() == 15) {
			return idCard15To18(idCard);
		}
		if (idCard.length() == 18) {
			return idCard18To15(idCard);
		}
		return idCard;
	}

	/**
	 * 得到身份证校验码
	 * 
	 * @param id
	 * @return
	 */
	public static boolean checkIdCard(String idCard) {
		if (idCard == null) {
			return false;
		}
		if (idCard.length() == 15) {
			idCard = swap15or18(idCard);
		}
		if (idCard.length() != 18) {
			return false;
		} else {
			char[] idCards = idCard.toCharArray();
			char verifyChar = idCards[17];
			char result = doVerify(idCards);
			if (result == verifyChar) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 得到身份证校验码
	 * 
	 * @param idCard
	 * @return
	 */
	private static char doVerify(char[] idCard) {
		int iS = 0;
		int i;
		for (i = 0; i < 17; i++) {
			iS += (int) (idCard[i] - '0') * iW[i];
		}
		int iY = iS % 11;
		return szVerCode[iY];
	}

	private static char[] szVerCode = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };

	private static int[] iW = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };

	public static void main(String[] args) {
		System.out.println(swap15or18("430105198010101010"));
		System.out.println(swap15or18("430105801010000"));
		System.out.println(checkIdCard("430105198010101010"));
	}
}
